import router from '@system.router';
import usbManager from '@ohos.usbManager';
import CheckEmptyUtils from '../../utils/CheckEmptyUtils.js';
import FileUtils from '../../utils/FileUtils.js';
import DateUtils from '../../utils/DateAndTimeUtil.js';
import EventConstants from '../../utils/EventConstants.js';
//import parameter from '@ohos.systemparameter';
import prompt from '@system.prompt';
import window from '@ohos.window';


export default {
    data: {
        device : [
                {
                    result: 'World',
                    device: null,
                    config: null,
                    pip: null,
                    inEndpoint: null,
                    outEndpoint: null,
                    interface: null,
                    usbRequest: null,
                    sendData: "",
                    isClaimed: false,
                    maxInSize: 1024,
                    maxOutSize: 1024,
                    beginTime: 0,
                    totalCount: 0,
                    successCount: 0,
                    isSending: false,
                    index: 0,
                    deviceName: ""
                },
                {
                    result: 'World',
                    device: null,
                    config: null,
                    pip: null,
                    inEndpoint: null,
                    outEndpoint: null,
                    interface: null,
                    usbRequest: null,
                    sendData: "",
                    isClaimed: false,
                    maxInSize: 1024,
                    maxOutSize: 1024,
                    beginTime: 0,
                    totalCount: 0,
                    successCount: 0,
                    isSending: false,
                    index: 0,
                    deviceName: ""
                }
        ]
    },
    onInit() {
        var index = this.indexParam;
        console.info("usb transfer device index : " + index);
        this.initData(0);
        this.initData(1);
    },
    initData(index) {
        this.device[index].index = index;
        var deviceList = usbManager.getDevices();
        if (CheckEmptyUtils.isEmptyArr(deviceList)) {
            this.result = "init error ： 设备列表为空";
            console.info("usb device is null");
            return;
        }
        let name = this.device[index].index + 1;
        if (deviceList.length - 1 < this.device[index].index) {
            this.device[index].result = "error ： 未插入设备" + name;
            console.info("usb device size is : " + deviceList.length);
            console.info("usb open index is : " + this.device[index].index);
            return;
        }
        this.device[index].device = deviceList[this.device[index].index];
        console.info("usb connectDevice device: " + JSON.stringify(this.device[index].device));
        this.device[index].deviceName = "设备" + name + " : " + this.device[index].device.name;
        try {
            this.device[index].pip = usbManager.connectDevice(this.device[index].device);
            if (CheckEmptyUtils.isEmpty(this.device[index].pip)) {
                this.device[index].result = "opendevice faild";
                console.info("usb opendevice pip is null");
                return;
            }
        } catch (err) {
            this.device[index].result = "设备打开失败：" + err;
            console.info("usb 设备打开失败：" + err);
            return;
        }

        console.info("usb connect back pip: " + JSON.stringify(this.device[index].pip));
        if (CheckEmptyUtils.isEmptyArr(this.device[index].device.configs)) {
            this.device[index].result = "init error ： 设备configs列表为空";
            console.info("usb request configs is null");
            return;
        }
        this.device[index].config = this.device[index].device.configs[0]

        console.info("usb request this.config: " + JSON.stringify(this.device[index].config));

        if (CheckEmptyUtils.isEmptyArr(this.device[index].config.interfaces)) {
            this.device[index].result = "init error ： 设备interfaces列表为空";
            console.info("usb request interfaces is null");
            return;
        }
        var interfaceSize = this.device[index].config.interfaces.length;
        console.info("usb request this.interface size: " + interfaceSize);

        for (let i = 0; i < interfaceSize; i++) {
            this.device[index].interface = this.device[index].config.interfaces[i];
            if (CheckEmptyUtils.isEmptyArr(this.device[index].interface.endpoints)) {
                continue;
            }
            // acm interface
            if (this.device[index].interface.clazz != 10 ||
                this.device[index].interface.subClass != 0 ||
                this.device[index].interface.protocol != 2) {
                continue;
            }
            // transfer endpoint
            for (let k = 0, len = this.device[index].interface.endpoints.length; k < len; k++) {
                let endpoint = this.device[index].interface.endpoints[k];
                if (endpoint.type == EventConstants.USB_ENDPOINT_XFER_BULK) {
                    if (endpoint.direction == EventConstants.USB_ENDPOINT_DIR_OUT) {
                        this.device[index].outEndpoint = endpoint;
                        this.device[index].maxOutSize = endpoint.maxPacketSize;
                    } else if (endpoint.direction == EventConstants.USB_ENDPOINT_DIR_IN) {
                        this.device[index].inEndpoint = endpoint
                        this.device[index].maxInSize = endpoint.maxPacketSize;
                    }
                }
            }

            if (!CheckEmptyUtils.isEmpty(this.device[index].outEndpoint)
                && !CheckEmptyUtils.isEmpty(this.device[index].inEndpoint)) {
                break;
            } else {
                this.device[index].outEndpoint = null;
                this.device[index].inEndpoint = null
            }
        }

        if (CheckEmptyUtils.isEmpty(this.device[index].outEndpoint) ||
            CheckEmptyUtils.isEmpty(this.device[index].inEndpoint)) {
            console.info("usb init failed, outEndpoint or inEndpoint is null");
            return;
        }

        console.info("usb request outEndpoint: " + JSON.stringify(this.device[index].outEndpoint));
        console.info("usb request inEndpoint: " + JSON.stringify(this.device[index].inEndpoint));

        this.device[index].isClaimed = usbManager.claimInterface(this.device[index].pip, this.device[index].interface, true) == 0;
        console.info("usb request,claimInterface " + this.device[index].isClaimed);
        if (!this.device[index].isClaimed) {
            this.device[index].result = "init error ： claimInterface failed";
        }
    },
    writeData24(index) {
        if (CheckEmptyUtils.isEmpty(this.device[index].pip)) {
            this.device[index].result = "write error ： 设备this.pip为空";
            console.info("usb request,writeData pip is null");
            return;
        }
        if (CheckEmptyUtils.isEmpty(this.device[index].outEndpoint)) {
            this.device[index].result = "write error ： 设备this.outEndpoint为空";
            console.info("usb request,writeData outEndpoint is null");
            return;
        }
        if (!this.device[index].isClaimed) {
            this.device[index].result = "write error ： claimInterface failed";
            console.info("usb request,write claimInterface failed");
            return;
        }
        if (this.device[index].isSending) {
            prompt.showToast({
                message: "已经开始发送了。。。",
                duration: 5000
            });
            return;
        }
        this.device[index].isSending = true;
        this.device[index].beginTime = (new Date()).getTime();
        this.device[index].totalCount = 0;
        this.device[index].successCount = 0;
        this.transfer(index);
    },
    transfer(index) {
        if (this.device[index].beginTime == 0) {
            this.device[index].isSending = false;
            return;
        }
        this.device[index].isSending = true;
        this.device[index].totalCount = this.device[index].totalCount + 1;
        var testData = "send milliseconds " + (new Date()).getTime();
        var tmpUint8Array = this.str2ab(testData);
        usbManager.bulkTransfer(this.device[index].pip, this.device[index].outEndpoint, tmpUint8Array, 15000).then(dataLength => {
            if (dataLength >= 0) {
                console.info("usb writeData result write length : " + dataLength);
            } else {
                console.info("writeData failed");
            }
            this.device[index].successCount = this.device[index].successCount + 1;
            this.device[index].result = "writeData24 total ：" +
                                        this.device[index].totalCount +
                                        " ; success:" +
                                        this.device[index].successCount;

            this.transfer(index);
        }).catch(error => {
            this.device[index].result = "writeData error ：" + JSON.stringify(error);
            console.info("usb writeData error : " + JSON.stringify(error));
            this.transfer(index);
        });
    },
    writeData241(){
        this.writeData24(0)
    },
    writeData242(){
        this.writeData24(1)
    },
    stopTransfer(index) {
        console.info("usb begin stopTransfer " + index);
        this.device[index].beginTime = 0;
        prompt.showToast({
            message: "停止发送。。。",
            duration: 5000
        });
    },
    stopTransfer1() {
        this.stopTransfer(0);
    },
    stopTransfer2() {
        this.stopTransfer(1);
    },
    BackRelease(index){
        if (CheckEmptyUtils.isEmpty(this.device[index].pip)) {
            return;
        }
        if (this.device[index].isClaimed) {
            let releaseStatus = usbManager.releaseInterface(this.device[index].pip, this.device[index].interface);
            console.info("usb request,releaseInterface : " + releaseStatus);
        }
        var isPipClose = usbManager.closePipe(this.device[index].pip);
        console.info("usb request,PipClose : " + isPipClose);
        router.back();
    },
    onBackPress() {
        this.BackRelease(0);
        this.BackRelease(1);
    },
// 字符串转为ArrayBuffer对象，参数为字符串
    str2ab(str) {
        var arr = [];
        for (var i = 0, j = str.length; i < j; ++i) {
            arr.push(str.charCodeAt(i));
        }
        var tmpUint8Array = new Uint8Array(arr);
        return tmpUint8Array;
    }
}
